package com.company.wechatpush.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.company.wechatpush.config.PushConfig;
import com.company.wechatpush.entity.Result;
import com.company.wechatpush.entity.User;
import com.company.wechatpush.entity.Weather;
import com.company.wechatpush.utils.RequestUtil;
import lombok.NonNull;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Real
 * @since 2022-09-03 12:12 AM
 */
public class WeatherService {
    public static Result<Weather> getWeather(User user) {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> map = new HashMap<>(4);
        map.put("district_id", user.getDistrictId());
        map.put("ak", PushConfig.getAk());
        String res = restTemplate.getForObject("https://api.map.baidu.com/weather/v1/?district_id={district_id}&data_type=all&ak={ak}", String.class, map);
        JSONObject json = JSONObject.parseObject(res);

        if (json == null) {
            // 接口地址有误或者接口没调通
            return Result.error(500, "天气接口不通，请检查接口地址！");
        }
        String status = json.getString("status");
        if (!"0".equals(status)) {
            return Result.error(Integer.parseInt(status), "天气接口调用报错: " + json.getString("message"));
        }
        JSONArray forecasts = json.getJSONObject("result").getJSONArray("forecasts");
        List<Weather> weathers = forecasts.toJavaList(Weather.class);
        Weather weather = weathers.get(0);
        JSONObject now = json.getJSONObject("result").getJSONObject("now");
        JSONObject location = json.getJSONObject("result").getJSONObject("location");
        weather.setTextNow(now.getString("text"));
        weather.setTemp(now.getString("temp"));
        weather.setCity(location.getString("city"));
        weather.setCityName(location.getString("name"));
        return Result.success(weather);
    }

    /**
     * 调用百度API获取天气
     *
     * @return
     */
    public static Result<Weather> getWeather(@NonNull String districtId) {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> map = new HashMap<>(4);
        map.put("district_id", districtId);
        map.put("ak", PushConfig.getAk());
        String res = restTemplate.getForObject("https://api.map.baidu.com/weather/v1/?district_id={district_id}&data_type=all&ak={ak}", String.class, map);
        JSONObject json = JSONObject.parseObject(res);

        if (json == null) {
            // 接口地址有误或者接口没调通
            return Result.error(500, "天气接口不通，请检查接口地址！");
        }
        String status = json.getString("status");
        if (!"0".equals(status)) {
            return Result.error(Integer.parseInt(status), "天气接口调用报错: " + json.getString("message"));
        }
        JSONArray forecasts = json.getJSONObject("result").getJSONArray("forecasts");
        List<Weather> weathers = forecasts.toJavaList(Weather.class);
        Weather weather = weathers.get(0);
        JSONObject now = json.getJSONObject("result").getJSONObject("now");
        JSONObject location = json.getJSONObject("result").getJSONObject("location");
        weather.setTextNow(now.getString("text"));
        weather.setTemp(now.getString("temp"));
        weather.setCity(location.getString("city"));
        weather.setCityName(location.getString("name"));
        return Result.success(weather);
    }

    /**
     * 请求天气诗句
     * {
     * "code": 200,
     * "msg": "success",
     * "newslist": [
     * {
     * "tqtype": 3,
     * "content": "东边日出西边雨，道是无晴却有晴",
     * "author": "刘禹锡",
     * "source": "竹枝词"
     * }
     * ]
     * }
     *
     * @param code
     * @return
     */
    public static Result<String> getWeatherPoem(Integer code) {
        String success = "200";
        String uri = "http://api.tianapi.com/tianqishiju/index?key=" + PushConfig.getTxKey() + "&tqtype=" + code;
        String jsonResult = RequestUtil.request(uri);
        JSONObject jsonObject = JSONObject.parseObject(jsonResult);
        String resultCode = jsonObject.getString("code");
        if (!success.equals(resultCode)) {
            return Result.error(500, "诗句请求失败，信息：" + jsonResult);
        }
        JSONArray newsList = jsonObject.getJSONArray("newslist");
        JSONObject data = newsList.getJSONObject(0);
        StringBuilder sb = new StringBuilder();
        String content = data.getString("content");
        sb.append(content).append("——");
        String author = data.getString("author");
        sb.append(author);
        String source = data.getString("source");
        sb.append("《").append(source).append("》");
        return Result.success(sb.toString());
    }
}
